package com.example.downloader;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.CheckBox;

public class DownloaderActivity extends Activity {
	private static final String TAG = "DownloaderActivity";

	SharedPreferences settings;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			//these need to be final to enable access in anonymous inner class
			final EditText fileNameField = (EditText) this.findViewById(R.id.editText1);
			final EditText downloadDelayField = (EditText) this.findViewById(R.id.editText2);
			final CheckBox chkDwnlr = (CheckBox) findViewById(R.id.togleDownloader);
			if ( Autostart.checkAlarm(DownloaderActivity.this) == true ) {
				chkDwnlr.setChecked(true);
			} else {
				chkDwnlr.setChecked(false);
			}
							
			settings = getSharedPreferences("settingPref", 0);

			View.OnClickListener handler = new View.OnClickListener(){
				public void onClick(View v) {
					Log.d(TAG, Integer.toString(v.getId()));
					switch (v.getId()) {
					
					case R.id.SaveSettings:
						String testFile = fileNameField.getText().toString();
						String downloadDelay = downloadDelayField.getText().toString();

						SharedPreferences.Editor editor = settings.edit();
						editor.putString("testFile", testFile);
						editor.putString("downloadDelay", downloadDelay);
						editor.commit();
						break;

					case R.id.LoadSettings:
						Log.d(TAG, "load settings");
						fileNameField.setText(settings.getString("testFile", null), TextView.BufferType.EDITABLE);
						downloadDelayField.setText(settings.getString("downloadDelay", null), TextView.BufferType.EDITABLE);
						break;
						
					case R.id.togleDownloader:
						if ( chkDwnlr.isChecked() )
							Autostart.createAlarm(DownloaderActivity.this);
						else
							Autostart.cancelAlarm(DownloaderActivity.this);
						break;
					}
				}
			};

			// Start listening these events
			findViewById(R.id.SaveSettings).setOnClickListener(handler);
			findViewById(R.id.LoadSettings).setOnClickListener(handler);
			findViewById(R.id.togleDownloader).setOnClickListener(handler);
				
		} catch(Exception e){
			Log.e(TAG, e.toString());
		}  
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
}